package com.midea.thread;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Semaphore;
import java.util.concurrent.atomic.AtomicBoolean;
//共享锁，许可证问题
public class TestSemphore {
    public static void main(String[] args) {
        List<PhoneRoom> rooms = new ArrayList<>();
        rooms.add(new PhoneRoom("Room1"));
        rooms.add(new PhoneRoom("Room2"));
        rooms.add(new PhoneRoom("Room3"));
        rooms.add(new PhoneRoom("Room4"));
        rooms.add(new PhoneRoom("Room5"));

        Semaphore s = new Semaphore(5);


        class Task implements Runnable{
            @Override
            public void run() {
                try {
                    s.acquire();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                for (int i=0;i< rooms.size();i++){
                    PhoneRoom room = rooms.get(i);
                    if (room.isFree()){
                        room.setFree(false);
                        System.out.println(Thread.currentThread().getName()+" entered"+room.getName());
                        try {
                            Thread.sleep(2000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        System.out.println(Thread.currentThread().getName()+" exited"+room.getName());
                        room.setFree(true);
                        s.release();
                        return;
                    }
                }
            }
        }

        for(int i = 0;i<10;i++){
            new Thread(new Task()).start();
        }

    }
}
class PhoneRoom{
    //不能用boolean,避免出现true时两个线程同时进入房间
    AtomicBoolean isFree = new AtomicBoolean(true);
    String name;



    public PhoneRoom(String name) {
        this.name = name;
    }
    public boolean isFree() {
        return isFree.get();
    }

    public void setFree(boolean flag) {
        this.isFree.set(flag);
    }
    public String getName() {
        return name;
    }
}